<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="产品编号" prop="productNumber">
        <!-- <el-input
          :disabled="[10].includes(formData.dictStatus) || ['view'].includes(formType)"
          v-model="formData.productNumber"
          placeholder="请输入产品编号"
        /> -->
        <el-select
          v-model="formData.productNumber"
          :disabled="[10].includes(formData.dictStatus) || ['view'].includes(formType)"
          filterable
          remote
          reserve-keyword
          placeholder="请选择产品编号"
          remote-show-suffix
          :remote-method="remoteMethod"
          @change="jobDropDown"
          :loading="loading"
        >
          <el-option
            v-for="(item, index) in options"
            :key="index"
            :label="item.productNumber"
            :value="item.productNumber"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <!-- <el-input
          :disabled="[10].includes(formData.dictStatus) || ['view'].includes(formType)"
          v-model="formData.productName"
          placeholder="请输入产品名称"
        /> -->
        <el-select
          v-model="formData.productName"
          :disabled="[10].includes(formData.dictStatus) || ['view'].includes(formType)"
          filterable
          remote
          reserve-keyword
          placeholder="请选择产品名称"
          remote-show-suffix
          :remote-method="remoteMethod"
          @change="userDropDown"
          :loading="loading"
        >
          <el-option
            v-for="(item, index) in options"
            :key="index"
            :label="item.productName"
            :value="item.productName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单类型" prop="dictOrderType">
        <el-select disabled v-model="formData.dictOrderType" placeholder="请选择订单类型">
          <el-option
            v-for="(dict, index) in getIntDictOptions(DICT_TYPE.MARKET_ORDER_TYPE)"
            :key="index"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否回收" prop="dictIsRecycle">
        <el-select
          :disabled="['view'].includes(formType)"
          v-model="formData.dictIsRecycle"
          placeholder="请输入是否回收"
        >
          <el-option
            v-for="(dict, index) in getIntDictOptions('dict_is_recycle')"
            :key="index"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          :disabled="['view'].includes(formType)"
          type="textarea"
          show-word-limit
          maxlength="50"
          v-model="formData.remark"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as DrawingRecycleApi from '@/api/technology/drawingRecycle'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const options = ref<any[]>([])
const formData = ref({
  id: undefined,
  productNumber: undefined,
  productName: undefined,
  dictOrderType: undefined,
  dictIsRecycle: undefined,
  remark: undefined,
  dictStatus: undefined as any,
  recyclePerson: undefined,
  recycleTime: undefined,
  updaterName: undefined,
  creatorName: undefined
})
const formRules = reactive({
  productNumber: [{ required: true, message: '产品编号不能为空', trigger: 'blur' }],
  productName: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
  dictIsRecycle: [{ required: true, message: '是否回收不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const loading = ref(false)

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type) === '新增' ? '新增' : '回收'
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DrawingRecycleApi.getDrawingRecycle(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DrawingRecycleApi.DrawingRecycleVO
    if (formType.value === 'create') {
      await DrawingRecycleApi.createDrawingRecycle(data)
      message.success(t('common.createSuccess'))
    } else {
      await DrawingRecycleApi.updateDrawingRecycle(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 产品 */
const remoteMethod = async (query: string) => {
  loading.value = true
  try {
    const data = await DrawingRecycleApi.productListDrawingRecycle(query)
    options.value = data
  } finally {
    loading.value = false
  }
}

/** 编号下拉选中 */
const jobDropDown = () => {
  options.value.map((item) => {
    if (formData.value.productNumber === item.productNumber) {
      formData.value.productName = item.productName
      formData.value.dictOrderType = item.dictOrderType
    }
  })
}
/** 名字下拉选中 */
const userDropDown = () => {
  options.value.map((item) => {
    if (formData.value.productName === item.productName) {
      formData.value.productNumber = item.productNumber
      formData.value.dictOrderType = item.dictOrderType
    }
  })
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    productNumber: undefined,
    productName: undefined,
    dictOrderType: undefined,
    dictIsRecycle: undefined,
    remark: undefined,
    dictStatus: undefined,
    recyclePerson: undefined,
    recycleTime: undefined,
    updaterName: undefined,
    creatorName: undefined
  }
  formRef.value?.resetFields()
}
</script>
